package com.phx.serialjni;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.ResolveInfo;
//import android.content.pm.*;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Message;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.TextView;


import com.phx.uart.uartJnit;
import com.utils.CRC16;

import java.lang.reflect.Field;
import java.util.List;

public class MainActivityo extends Activity  implements SeekBar.OnSeekBarChangeListener {

    private SeekBar seekBar;
    private SeekBar seekBar1;
    private SeekBar seekBar2;
    private TextView tv1;
    private TextView tv2;
    myFrameLayout frame;
    int maxC = 0;
    public int currentPosition = -1;
    JBtnView newm;
    TextView testView;
    int currentPage = 0;
    private static final long TIMER_INTERVAL = 100;
    PageJ pagestatus = new PageJ();
    Rect currentRect = new Rect();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_omain);
        // seekBar=(SeekBar) findViewById(R.id.brseekBar);
        tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        testView = new TextView(this);
        //这里的Textview的父layout是ListView，所以要用ListView.LayoutParams
        //  ListView.LayoutParams layoutParams = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ListView.LayoutParams.WRAP_CONTENT);
        // textView.setLayoutParams(layoutParams);
        testView.setPadding(20, 0, 20, 0);
        testView.setText("this is used for testing");
        testView.setTextColor(getResources().getColor(R.color.colorAccent));
        testView.setTextSize(18);
        seekBar = new SeekBar(this);


//        <SeekBar
//        android:id="@+id/brseekBar"
//        android:layout_width="280dp"
//        android:layout_height="wrap_content"
//        android:layout_gravity="top|left"
//        android:layout_marginTop="300dip"
//        android:maxHeight="3dip"
//        android:minHeight="3dip"
//        android:progressDrawable="@drawable/adjust"
//        android:thumb="@drawable/thumb_image"
//        android:thumbOffset="0dip"></SeekBar>
        seekBar.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar.setMinimumHeight(convertHn(3));
        seekBar.setOnSeekBarChangeListener(this);
        seekBar.setThumbOffset(0);
        frame = (myFrameLayout) findViewById(R.id.gridlayout1);
        //  seekBar.buildLayer();
        // seekBar.setTop(100);
        //    seekBar.setLeft(500);
        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(376), convertHn(46));
        //   View headGroupView = UIUtils.inflate(mContext,R.layout.circle_head_layout);
//        RelativeLayout rlHead = (RelativeLayout)headGroupView.findViewById(R.id.rl_circle_head);
//        ImageView headImage = (ImageView)headGroupView.findViewById(R.id.iv_head_small);
        headParams.setMargins(convertWn(566), convertHn(163), convertWn(936), convertHn(198));
        // headGroupView.setLayoutParams(headParams);
        seekBar.setLayoutParams(headParams);
        frame.addView(testView);
        frame.addView(seekBar);
        // seekBar.setPadding(500,100, 50,700);
        seekBar.bringToFront();
        // PageS.setfeeds();
//        seekBar.setTop(350);
//        seekBar.setBottom(100);
//     //   seekBar.setThumb(getDrawable(R.drawable.barseat_1_on));
//        seekBar.setThumbOffset(0);
        seekBar.setSplitTrack(false);
        seekBar1 = new SeekBar(this);

        //seekBar.setMin(1);
        seekBar.setMax(100);
        seekBar1.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar1.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar1.setMinimumHeight(convertHn(3));
        seekBar1.setOnSeekBarChangeListener(this);
        seekBar1.setThumbOffset(0);
        FrameLayout.LayoutParams headParams1 = new FrameLayout.LayoutParams(convertWn(376), convertHn(46));
        headParams1.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        seekBar1.setLayoutParams(headParams1);
        frame.addView(seekBar1);
        // seekBar.setPadding(500,100, 50,700);
        seekBar1.bringToFront();
        seekBar1.setSplitTrack(false);
        seekBar2 = new SeekBar(this);

        // seekBar1.setPadding(0,0,0,0);
        seekBar2.setThumb(getDrawable(R.drawable.thumb_image));
        seekBar2.setProgressDrawable(getDrawable(R.drawable.adjust));
        seekBar2.setMinimumHeight(convertHn(3));
        seekBar2.setOnSeekBarChangeListener(this);
        seekBar2.setThumbOffset(0);

        seekBar.setTag(0);
        seekBar1.setTag(1);
        seekBar2.setTag(2);
        FrameLayout.LayoutParams headParams2 = new FrameLayout.LayoutParams(convertWn(376), convertHn(46));
        headParams2.setMargins(convertWn(566), convertHn(360), convertWn(936), convertHn(395));
        seekBar2.setLayoutParams(headParams2);
        frame.addView(seekBar2);
        // seekBar.setPadding(500,100, 50,700);
        seekBar2.bringToFront();
        seekBar2.setSplitTrack(false);
//        //seekBar.setPadding(19,19,300,80);
//        //seekBar.setLeft(50);
//       // seekBar.setLayoutParams(layoutParams);
//       // seekBar.setMax(400);
//        //   seekBar.setProgress(50);
//        seekBar.setBackground(getDrawable(R.drawable.adjust));
        //seekBar.setDrawingCacheBackgroundColor(Color.DKGRAY);

        //   seekBar.setMinimumHeight(4);

        // seekBar.setMax(48);
//        try {
//            Class<?> superclass = seekBar.getClass().getSuperclass().getSuperclass();
//            Field mMaxHeight = superclass.getDeclaredField("mMaxHeight");
//            mMaxHeight.setAccessible(true);
//          //  mMaxHeight.set(seekBar,FormatUtils.dip2px(2,context));
//            mMaxHeight.set(seekBar,10);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        // this.add
        //frame.addView(seekBar);
        // refreshui();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //frame.addView(seekBar,2);


        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;


    }


    public void slidersend(int seekno,int sseq )
    {
        String cmdx = PageS.sliderCmd[seekno][sseq];
        // String tmpTmp = "C1200009";
        String cmdheader = "5AA50883";
        String feedheader = "5AA5";
        String allCmdx = cmdheader;
        String tmpTmp = cmdx;
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        // String crcString = "83192001001F";
        //  String crcString =  pagestatus.cmdArray[currentPosition];
        //  String nexts = "5aa5078200030000ac1e";
        // String crcString = cmdOne ;
        //   StringBuffer exCmd = CRC16.crc16(crcString);
         new Thread() {
             public void run() {
                 super.run();
                 try {
                     //   if (uartJint != null) {
                     boolean isSendx = false;
                     isSendx = uartJnit.getInstance().sendCmds(cmd);
                     Log.e("send TAG", "send down: " + cmd);
                     Message msg = new Message();
                     if (isSendx) {
                         //  msg.what = 1;

                         Log.e("send TAG", "send down" + cmd + "success");
                     } else {
                         Log.e("TAG", "send down  :" + cmd + "failed!");
                     }
                     //    }
//
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
                 try {
                     Thread.sleep((long) TIMER_INTERVAL);
                 } catch (InterruptedException e2) {
                     e2.printStackTrace();

                 }
             }


         }.start();
}
    //数值改变
    @Override
    public void onProgressChanged(SeekBar seekBarx, int progress,
                                  boolean fromUser) {
        // TODO Auto-generated method stub
        tv1.setText("正在拖动");
      //  testView.setText("当前数值："+progress);
        int type = 0;
        int tmp = (int) seekBarx.getTag();
            int firpara = progress / 10;
            //  testView.setText("当前数值："+ firpara);
            String cmdx = PageS.sliderCmd[tmp][firpara];
            if (progress  % 10 == 0) {
                testView.setText("当前数值：" + cmdx);

                slidersend(tmp,firpara);
            }


    }

    //开始拖动
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
        tv1.setText("开始拖动");
    }

    //停止拖动
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
        tv1.setText("停止拖动");
    }



    public void removeAll()
    {
        if (frame != null) {
            frame.removeAllViews();
            frame.invalidate();
        }
        maxC = 0;
    }

    void refreshui()
    {


        removeAll();

        JBtnView mezi = new JBtnView(MainActivityo.this);


        mezi.bitmapX = 100;
        mezi.bitmapY = 0;
        mezi.mleft = convertW(0);
        mezi.mtop = convertH(0);
        mezi.mwidth = convertW(10);
        mezi.mheight = convertH(10);
        mezi.mRes = R.drawable.b2_off;
        mezi.type = 1;
        mezi.setClickable(true);


        mezi.setId(0);
        // frame.setTag(allCmd.toString());
        mezi.setOnTouchListener(new MainActivityo.TouchListenerx());

        frame.addView(mezi,-1);
      //  frame.setBackgroundResource(PageS.pageback);
        //   frame.setBackgroundResource(R.drawable.a6);
        // frame.addView(mezi,0);
        // frame.invalidate();

        addmezis();


    }
    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    int diptopx(int dps) {
        return Math.round(getResources().getDisplayMetrics().density * dps);
    }
    public int convertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = oldx * screenWidth / 2048;

        return newx;

    }

    public int convertWn(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = oldx * screenWidth / 1024;

        return newx;

    }
    public  Rect convertRect(Rect old)
    {
        return  new Rect(convertW(old.left),convertH(old.top),convertW(old.right),convertH(old.bottom));
    }
    public int convertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (old * screenHeight) / 1536;

        return newx;

    }
    public int convertHn(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (old * screenHeight) / 600;

        return newx;

    }


    protected int rconvertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (oldx *  2048) / screenWidth;

        return newx;

    }



    protected int rconvertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (1536 * old) / screenHeight;

        return newx;

    }

    protected View createButton(int index) {
        final Button btn = new Button(this);
        btn.setId(index++);
        Log.d("da", "id is" + btn.getId());

        btn.setWidth(40);
        btn.setHeight(100);
        //GridLayout.LayoutParams mParams = new GridLayout.LayoutParams(
        //btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
        //       LinearLayout.LayoutParams.WRAP_CONTENT));
        // btn.set
        // btn.setLayoutParams(new GridLayout.LayoutParams(GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.MATCH_PARENT));
        btn.setText("okc");
        return btn;
    }


    public  void addmezis()
    {


        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp =PageJ.allRect.length;
        maxC = tmp ;
        for (int w=0; w<tmp;w++) {
            // tmprecto = convertRect(PageS.allRect[w]);


            tmprecto = PageJ.allRect[w];
            JBtnView mezii = new JBtnView(MainActivityo.this);

            // mezi.setOnTouchListener(new OnTouchListener() {
            //  @Override
            // public boolean onTouch(View view, MotionEvent event) {


            //  mezi.bitmapX = 100;
            //  mezi.bitmapY = 0;
            mezii.mleft = convertW(tmprecto.left);
            mezii.mtop = convertH(tmprecto.top);
            mezii.mwidth = convertW(tmprecto.width());
            mezii.mheight = convertH(tmprecto.height());

            mezii.mRes = PageJ.offArray[w];
            String addr = PageJ.feedDArray[w];
            boolean bool1 = PageJ.feedMap.containsKey(addr);
            String tmpS = PageJ.feedMap.get(addr);
            boolean bool2 = (tmpS == null)? false:(tmpS.equals("0001"));


            mezii.type = PageJ.nodeArray[w];
            //   mezii.setClickable(true);

            // mezi.setTag(allCmd.toString());
            mezii.setId(w + 1);
            // frame.setTag(allCmd.toString());
            // mezii.setOnTouchListener(new TouchListenerx());

            //  frame.addView(mezi,0);
            //  frame.setBackgroundResource(pagestatus.pageback);
            // frame.addView(mezii);
            frame.addView(mezii,w);
            if(bool1 && bool2)
            {
                mezii.mRes = PageJ.onArray[w];
                mezii.repaint();
                //testFeed(w,true);
            }
            //  testFeed(6);
            // frame.getChildAt()
        }
    }


    private void openApp(String packageName, String actName ,Context cx) {
//        PackageInfo pi = cx.getPackageManager().getPackageInfo(packageName, 0);
//
//        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
//        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//        resolveIntent.setPackage(pi.packageName);
//
//        List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);
//
//        ResolveInfo ri = apps.iterator().next();
//        if (ri != null ) {
//            String packageName = ri.activityInfo.packageName;
//            String className = ri.activityInfo.name;
//
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.addCategory(Intent.CATEGORY_LAUNCHER);
//
//            ComponentName cn = new ComponentName(packageName, className);
//
//            intent.setComponent(cn);
            // startActivity(intent);

        Intent intent=new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(new ComponentName(packageName, actName));
        cx.startActivity(intent);
        }


    @Override
    protected void onDestroy() {
        // uartJni.close(fd);
        uartJnit.sclose();
        super.onDestroy();
    }
    private class TouchListenerx implements View.OnTouchListener {
        private boolean longClicked;
        private boolean upClicked;
        private int downtimes = 0;
        private int uptimes = 0;
        private int failTime;
       // private IBackService xBackService;
//        private TouchListenerx(IBackService abak) {
//         //   xBackService = abak;
//        }

        private TouchListenerx() {
            //   xBackService = abak;
        }


        int getCurSel(Rect[] allrect ,int x,int y)
        {

            //  if (tempRect.contains((int) x, (int) (y)))
            Rect tmprect = new Rect() ;
            Rect tmprecto = new Rect() ;
            int tmp = allrect.length;
            for (int w=0; w<tmp;w++)
            {
                tmprecto = convertRect(allrect[w]);
                if (tmprecto.contains(x,y))
                {
                    tmprect = tmprecto;
                    return  w;
                }
            }
            return  -1;
        }


        public boolean onTouch(View v, MotionEvent event) {

            //  iBackService.
            int x = (int) event.getX();
            int y = (int) event.getY();
            currentPosition = getCurSel(PageJ.allRect,x,y);

            Log.e("touchTAG", "view:"  + v.getId());


            if(currentPosition!=-1){
                String cmdOne = PageJ.cmdArray[currentPosition];
                int mmtype = pagestatus.typeArray[currentPosition];


                // pageS.
                if (mmtype == 29)
                {
                   // pagestatus.cmdArray[1]

                }


                }


            return  true;
        }
    }

}
